package com.util;
import java.io.InputStream;  
import java.sql.Connection;  
import java.sql.DriverManager;  
import java.sql.PreparedStatement;
import java.sql.ResultSet;  
import java.sql.SQLException;  
import java.sql.Statement;  
import java.util.Properties;  

public class JdbcUtil {  
    public static Connection getConnection(String jdbcProperties) throws Exception {  
        Properties properties = new Properties();  
        InputStream inStream = JdbcUtil.class.getClassLoader().getResourceAsStream(jdbcProperties);  
        properties.load(inStream);  
  
        // 1. 准备获取连接的 4 个字符串: user, password, url, jdbcDriver
        String user = properties.getProperty("jdbc.userName");  
        String password = properties.getProperty("jdbc.password");  
        String url= properties.getProperty("jdbc.url");  
        String jdbcDriver= properties.getProperty("jdbc.driverClassName");  
  
        // 2. 加载驱动: Class.forName(driverClass)  
        Class.forName(jdbcDriver);  
  
        // 3.获取数据库连接  
        Connection connection = DriverManager.getConnection(url, user, password);  
        return connection;  
    }  
  
    public static void releaseDB(PreparedStatement ps) {  
        if (ps != null) {  
            try {  
            	ps.close();  
            } catch (SQLException e) {  
                e.printStackTrace();  
            }  
        }  
    } 

    public static void releaseDB(ResultSet resultSet, Statement statement, Connection connection) {  
        if (resultSet != null) {  
            try {  
                resultSet.close();  
            } catch (SQLException e) {  
                e.printStackTrace();  
            }  
        }  
  
        if (statement != null) {  
            try {  
                statement.close();  
            } catch (SQLException e) {  
                e.printStackTrace();  
            }  
        }  
  
        if (connection != null) {  
            try {  
                connection.close();  
            } catch (SQLException e) {  
                e.printStackTrace();  
            }  
        }  
    }  
} 